﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SRF.Common;
using SRF.Admin;
using SRF.Admin.Models;
using System.Linq.Expressions;
using SRF.UI.Html;
using SRF.UI.View;

namespace SRF.Web.Areas.Admin.Controllers
{
    [SRF.Security.Authorize]
    [SRF.Common.Logging.Log]
    public class UserController : Controller
    {
        static SRF.Common.Logging.ILog logger = SRF.Common.Logging.LogManager.GetLogger("UserController");

        UserService userService = ObjectHelper.GetObject<UserService>();
        RoleService roleService = ObjectHelper.GetObject<RoleService>();
        DepartmentService departmentService = ObjectHelper.GetObject<DepartmentService>();

        //
        // GET: /Admin/User/  
        //[SRF.UI.ViewTitle("用户列表")]
        public ActionResult List()
        {
            SRF.UI.DataSource datasource = new UI.DataSource("admin.user.list", "admin.user.count", m => { m.Like("name"); });//给参数name的值加上通配符
            datasource.PerPageSize = 10;

            return View(datasource);
        }

        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        public ActionResult Edit(string id)
        {
            ViewBag.DepartmentList = departmentService.List();
            IList<SelectListItem> roleList = new List<SelectListItem>();
            foreach (Role role in roleService.List())
            {
                roleList.Add(new SelectListItem() { Text = role.Name, Value = role.Id });
            }
            ViewBag.RoleList = roleList;
            if (string.IsNullOrEmpty(id))
            {
                ViewData["title"] = "新增用户";

                return View(new User() { Enabled = true });
            }
            else
            {
                ViewData["title"] = "编辑用户";
                var user = userService.Get(id);
                user.Roles = userService.GetRoles(id);

                return View(user);
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(User user)
        {
            ViewBag.DepartmentList = departmentService.List();
            var id = userService.Save(user);
            if (Request.IsAjaxRequest())
            {
                return Content(id);
            }
            else
            {
                return RedirectToAction("Edit", "User", new { id = id });
            }
        }

        /// <summary>
        /// 查看用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        public ActionResult View(string id)
        {
            ViewBag.DepartmentList = departmentService.List();
            if (!string.IsNullOrEmpty(id))
            {
                var user = userService.Get(id);
                user.Roles = userService.GetRoles(id);

                IList<SelectListItem> roleList = new List<SelectListItem>();
                foreach (Role role in roleService.List())
                {
                    roleList.Add(new SelectListItem() { Text = role.Name, Value = role.Id });
                }
                ViewBag.RoleList = roleList;

                return View(user);
            }
            else
                return View();
        }

        public ActionResult Delete(string id)
        {
            if (Security.SecurityContext.User.Id == id)
            {
                return Content("不能删除当前用户");
            }
            else
            {
                userService.Delete(id);
                return new EmptyResult();
            }
        }

        public ActionResult SetPassword(string loginId)
        {
            Models.ChangePasswordModel model = new Models.ChangePasswordModel()
            {
                LoginId = loginId
            };

            return View(model);
        }
        [HttpPost]
        public ActionResult SetPassword(Models.ChangePasswordModel model)
        {
            Security.SecurityContext.SecurityProvider.ChangePassword(model.LoginId, model.NewPassword, "");

            if (Request.IsAjaxRequest())
            {
                return new EmptyResult();
            }
            else
            {
                return RedirectToAction("SetPassword", "User", model);
            }
        }

        public ActionResult UserProfile()
        {    
            var user = userService.Get(SRF.Security.SecurityContext.User.Id); 

            return View(user);
        }
        public ActionResult SavePersonal(SRF.Admin.Models.User user)
        {
            if (Request.IsAjaxRequest())
            {
                userService.SavePersonal(user);

                return new EmptyResult();
            }
            else
            {
                return View();
            }
        }
        [HttpPost]
        public ActionResult ChangePassword(Models.ChangePasswordModel model)
        {
            if (Request.IsAjaxRequest())
            {
                try
                {
                    Security.SecurityContext.SecurityProvider.ChangePassword(
                        Security.SecurityContext.User.LoginId,
                        model.NewPassword,
                        model.OldPassword);
                    return new EmptyResult();
                }
                catch (SRF.Security.Exceptions.PasswordWrongException)
                {
                    return this.Exception("旧密码不正确", 500);
                }
                catch (Exception ex)
                {
                    return this.Exception(ex.Message, 500);
                }
            }
            else
            {
                return View(model);
            }
        }

        protected override void OnException(ExceptionContext filterContext)
        {
            logger.Error(filterContext.RouteData.Values["action"], filterContext.Exception);

            base.OnException(filterContext);
        }
    }
}